//
//  StudyDataPushManager.swift
//  SitPosition
//
//  Created by apple on 2019/2/12.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation


/**
 * 学习姿态数据推送管理器
 * 上传成功后由该组件负责将学习姿态数据推送到后台服务器
 */
struct StudyDataPushManager {
    
    // MARK: - Properties
    
    // 单例
    public static let manager = StudyDataPushManager()
    // 事件处理队列
    private let eventQueue: OperationQueue = OperationQueue()
    
    // 启动
    public func start() {
        NotificationCenter.default
            .addObserver(forName: NSNotification.Name.uploadSuccess, object: nil, queue: eventQueue) { (note) in
            self._handleUploadSuccessNotification(note)
        }
        NotificationCenter.default
            .addObserver(forName: NSNotification.Name.uploadFailure, object: nil, queue: eventQueue) { (note) in
            self._handleUploadFailureNotification(note)
        }
    }
}


// MARK: - Private Methods

extension StudyDataPushManager {
    
    private func _handleUploadSuccessNotification(_ note: Notification) {
        guard let uploadTaskKeys: [String] = note.object as? [String],
            let uploadTasks: [UploadTask] = UploadTask.all(by: uploadTaskKeys) else {
            return
        }
        
        let decoder: JSONDecoder = JSONDecoder()
        let spds: [StudyPoseData] = uploadTasks.map { (task) -> StudyPoseData? in
            guard let url: String = task.url,
                let extraData: Data = task.extra?.data(using: String.Encoding.utf8) else {
                return nil
            }
            guard let spd: StudyPoseData = try? decoder.decode(StudyPoseData.self, from: extraData) else {
                return nil
            }
            return StudyPoseData(url: url, type: spd.type,
                                 uploadTime: spd.uploadTime,
                                 duration: spd.duration)
        }.filter { $0 != nil }
            .map { $0! }
        
        let keys: [String] = uploadTasks.map { $0.key }
        NetworkClient.instance.batchSaveStudentPoseData(contents: spds, success: { (data) in
            uploadTasks.forEach({ (task) in
                if let cacheFilePath: String = try? task.localCacheFilePath() {
                    try? FileManager.default.removeItem(atPath: cacheFilePath)
                }
            })
            UploadTask.delete(by: keys)
        }) { (error) in
            dbgPrint("ERROR: failed to batch save student pose data \(keys), occured error: \(error?.localizedDescription ?? Strings.errUnknown)")
        }
    }
    
    private func _handleUploadFailureNotification(_ note: Notification) {
        guard let uploadTaskKeys: [String] = note.object as? [String],
            let uploadTasks: [UploadTask] = UploadTask.all(by: uploadTaskKeys) else {
            return
        }
        let keys: [String] = uploadTasks.map { $0.key }
        dbgPrint("ERROR: failed to qiniu upload: \(keys)")
    }
    
}
